package com.nulldev.util.web.HttpServer3.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.io.IOUtils;

public class SectionedInputStreamTest {

	private static String readTillNextLine(final InputStream is) throws Exception {
		final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(IOUtils.STRING_ALLOC_BUFFER);
		int c;
		while ((c = is.read()) != -1) { // BufferedReader
			if (c == ((char) '\r') || c == ((char) '\n')) {
				if (c == ((char) '\r'))
					is.read();
				break;
			}
			byteArrayOutputStream.write(c);
		}
		if (c == -1 && byteArrayOutputStream.size() == 0) {
			return null;
		}
		final String line = byteArrayOutputStream.toString("UTF-8");
		IOUtils.closeQuietly(byteArrayOutputStream);
		return line;
	}

	public static void main(String[] args) throws Exception {
		final int REGULAR_REQUEST_DETECTION_SIZE = 4;
		final String init0 = "GET ";
		final String init1 = "/ HTTP/1.1";

		final ByteArrayInputStream i0 = new ByteArrayInputStream(init0.getBytes());
		final ByteArrayInputStream i1 = new ByteArrayInputStream(init1.getBytes());

		final SectionedInputStream si = new SectionedInputStream(i0, REGULAR_REQUEST_DETECTION_SIZE);
		final byte[] initData = new byte[REGULAR_REQUEST_DETECTION_SIZE];
		si.read(initData);
		IOUtils.closeQuietly(si);

		JVM.println("initData: " + new String(initData));
		final InputStream is = new SequenceInputStream(si, i1);
		JVM.println("r0: " + readTillNextLine(is));
		IOUtils.closeQuietly(is);
	}

}
